<?php

namespace app\traits;

use support\Model;
use Illuminate\Support\Facades\Log;

/**
 * 表
 * Trait TableCreateTrait
 * @package App\Traits
 */
trait TableTrait
{
    public static $TABLE_PERIOD = 0;
    public static $TABLE_PERIOD_YM = 1;
    public static $TABLE_PERIOD_YW = 2;
    public static $TABLE_PERIOD_YMD = 3;

    //数据表不存在
    public static $TABLE_NOT_FOUND = "42s02";

    private $tips = [
        0 => '',//只一张表
        1 => 'Ym',//按月
        2 => 'YW',//按周
        3 => 'Ymd',//按日
    ];

    /**
     * 获取表名
     * @param string $tableName 表名字
     * @param int $period 分表规则 0只建一张表 1按月 2按周 3按日
     * @param int $time 时间
     * @return string
     */
    public function getTableName($tableName, $period = 0, $time = 0)
    {
        $tmp = isset($this->tips[$period]) ? $this->tips[$period] : '';
        if ($tmp) {
            $time = empty($time) ? time() : $time;
            $tableName = $tableName . date($tmp, $time);
        }
        return $tableName;
    }

    /**
     * 创建表
     * @param Model $dbName 数据库连接
     * @param string $baseTableName 表名
     * @param int $period 分表规则 0只建一张表 1按月 2按周 3按日
     * @param int $time 时间
     * @return bool
     */
    public function createTable(Model $dbName, $baseTableName, $period = 0, $time = 0)
    {
        $newTableName = $this->getTableName($baseTableName, $period, $time);
        try {

            $sql = sprintf("CREATE TABLE IF NOT EXISTS %s LIKE %s", $newTableName, $baseTableName);
            return $dbName->select($sql);

        } catch (\Exception $e) {

            Log::info(__METHOD__ . 'CREATE SQL ERROR:' . $e->getMessage());
            return false;
        }
    }
}